<?php
namespace app\wxadmin\model;
use think\Db;

class User
{
    /**
     * 获取企业的部门josn，用户layui的tree
     * @param string $corpid
     * @return json|stringn
     */
    function get_dept_json($corpid='')
    {
        $data = Db::name('dept')->field('dept_id as id,parentid as pid,name')->order('sort desc')->select();
        $res = [];
        $tree = [];
        //整理数组
        foreach( $data as $key=>$vo ){
            $res[$vo['id']] = $vo;
            $res[$vo['id']]['children'] = [];
        }
        unset( $data );

        //查询子孙
        foreach( $res as $key=>$vo ){
            if( $vo['pid'] != 0 ){
                $res[$vo['pid']]['children'][] = &$res[$key];
            }
        }

        //去除杂质
        foreach( $res as $key=>$vo ){
            if( $vo['pid'] == 0 ){
                $tree[] = $vo;
            }
        }
        unset( $res );

        $tree = json_encode( $tree );
        return $tree;
    }


    function get_dept_child($arrCat, $parent_id = 0, $level = 0)
    {
        static  $arrTree = array(); //使用static代替global
        if( empty($arrCat)) return FALSE;
        $level++;
        foreach($arrCat as $key => $value)
        {
            if($value['parentid' ] == $parent_id)
            {
                $arrTree[] = $value;
                unset($arrCat[$key]); //注销当前节点数据，减少已无用的遍历
                $this->get_dept_child($arrCat, $value['dept_id'], $level);
            }
        }
        return $arrTree;
    }

    /**
     * @param $corpid
     * @param $dept_id
     * @return array
     */
    function get_dept_ids($corpid,$dept_id)
    {
        $db=Cdb::db($corpid);
        $data = $db->name('dept')->order('sort desc')->select();
        $this->get_dept_child($data,$dept_id);
        return $ids;
    }
}